<template>
    <div class="seach-list">
        <div class="gmvst-profile ">
            <div class="gmvst-server fl forscroll">
                <ul>
                    <li @click="areaClick(0)" :class="{curren:isQuanqu && !isHis}"><span
                            class="border-bottom f30 color-000 pl-30 mr-30">全区</span></li>
                    <li
                            v-for="(elem, index) in gameAreaList"
                            :class="{curren:matchCurren(index)&&!isQuanqu&&!isHis}"
                            @click="areaClick(elem)"
                    ><span class="border-bottom f30 color-000 pl-30 mr-30">{{elem.name}}</span></li>
                    <li @click="areaClick('his')" :class="{curren:isHis}" v-if="$route.params.goodsType == 2">
                      <span class="border-bottom f30 color-000 pl-30 mr-30">历史记录</span></li>
                </ul>
            </div>
            <div class="gmvst-area bg-fff">
                <div class="gmvst-server" v-if="!isHis">
                    <div class="gvst-seach mx-30 my-20 border py-15 px-20">
                        <input class="server-input color-333 f30" type="text" placeholder="请输入服务器名称"
                               v-model="gsSearchInput">
                        <div class="login-del" @click="isDels()">
                            <a class="del"></a>
                        </div>
                    </div>
                </div>
                <!-- 服列表 -->
                <ul class="pl-30" v-if="gameServerListFilter.length>0&&!isQuanqu&&!isHis">
                    <li
                            v-for="(elem, index) in gameServerListFilter"
                            :class="{active:postData.selectGameServerId==elem.id}"
                            @click="serverClick(elem)"
                            class="border-bottom pr-30">
                        <span class="f30 color-000">{{elem.name}}</span>
                    </li>
                </ul>
                <!--端游历史纪录列表-->
                <ul class="pl-30" style="margin-top: 0" v-if="isHis">
                    <li class="border-bottom pr-30"
                        v-for="(item,index) in historyList"
                        v-show="index < 20"
                        @click="hisClick(item)"
                        style="line-height: 0.48rem; padding: 0.3rem 0.3rem 0.3rem 0px;"
                    >
                        <span v-if="item.regionName"  class="f30 color-000 " >{{item.regionName}}/{{item.serverName}}</span>
                    </li>
                </ul>
                <ul class="pl-30" v-else-if="isQuanqu" @touchmove.prevent>
                    <li @click="serverClick(0)" v-if="isQuanqu" :class="{active:isQuanfu}"><span
                            class="border-bottom f30 color-000" style="display: block">全服</span></li>
                </ul>
                <ul class="pl-30" v-else @touchmove.prevent>
                    <li
                            class="border-bottom pr-30">
                        <span class="f30 color-000">暂无服务器</span>
                    </li>
                </ul>
            </div>
        </div>
        <div class="shade" @click="shadeClick" @touchmove.prevent></div>
    </div>
</template>
<script>
import { mapState, mapGetters, mapActions } from "vuex";
export default {
  data() {
    return {
      gsSearchInput: "",
      isQuanqu: false,
      isServer: false,
      isQuanfu: false,
      isHis: false,
      historyList: []
    };
  },
  props: ["AllServer", "isFromName"],
  async created() {
    if (this.AllServer == "全区全服") {
      this.isQuanqu = true;
      this.isQuanfu = true;
    } else {
      this.isQuanqu = false;
      this.isQuanfu = false;
    }
   
  },

  computed: {
    gameServerListFilter: function() {
      var str = this.gsSearchInput.toLowerCase();
      if (this.gameServerList) {
        if (str) {
          return this.gameServerList.filter(function(item) {
            return item.name.toLowerCase().indexOf(str) !== -1;
          });
        } else {
          return this.gameServerList;
        }
      }
    },
    ...mapState({
      postData: state => {
        return state.choice.postData;
      },
      gameAreaList: state => {
        return state.choice.gameAreaList;
      },
      gameServerList: state => {
        return state.choice.gameServerList;
      }
    })
  },
  mounted() {
    document.body.style.overflow = "hidden";
    document.body.style.position = "fixed";
    document.body.style.width = "100%";
    document.body.style.top = "0";
    if (document.getElementById("istScroll")) {
      document.getElementById("istScroll").style.position = "fixed";
      document.getElementById("istScroll").style.overflow = "hidden";
      document.getElementById("istScroll").style.width = "100%";
      document.getElementById("istScroll").style.top = "0";
    }
    if (document.getElementById("istwoScroll")) {
      document.getElementById("istwoScroll").style.position = "fixed";
      document.getElementById("istwoScroll").style.overflow = "hidden";
      document.getElementById("istwoScroll").style.width = "100%";
      document.getElementById("istwoScroll").style.top = "0";
    }
  },
  destroyed() {
    document.body.style.overflow = "visible";
    document.body.style.position = "relative";
    if (document.getElementById("istScroll")) {
      document.getElementById("istScroll").style.position = "relative";
      document.getElementById("istScroll").style.overflow = "auto";
    }
    if (document.getElementById("istwoScroll")) {
      document.getElementById("istwoScroll").style.position = "relative";
      document.getElementById("istwoScroll").style.overflow = "auto";
	  document.getElementById("istwoScroll").style.marginBottom = "0";
    }
  },
  methods: {
    // 获取服务器历史记录数据
    getHistoryList() {
      return new Promise((resolve, reject) => {
        this.$http
          .post(
            this.$CONSTANTS.APISearch +
              "regionServerHistory/queryCategoryHistory",
            { gameId: this.$route.params.gameId }
          )
          .then(
            res => {
              if (res.body.responseStatus.code == "00") {
                resolve(res.body.result);
              }
            },
            error => {
              reject(error);
              
            }
          );
      });
    },
    isDels() {
      this.gsSearchInput = "";
    },
    shadeClick() {
      this.$parent.serverShow();
    },

    matchCurren(i) {
      if (this.postData.selectGameAreaId) {
//        if(this.$route.params.goodsType=="2"){
          if (this.gameAreaList[i].id==this.postData.selectGameAreaId) {
            return true
          }
//        }else{
//          if (this.gameAreaList[i].catagoryId==this.postData.selectGameAreaId) {
//            return true
//          }
//
//        }

      } else {
        return false;
      }
      return false;
    },
    serverClick(e){
      // console.log('--55----',e)
      if(e==0){
        this.isQuanqu = false
        this.$parent.displayServerName = "全区全服"

        this.$parent.selectGameServerId = null;

        this.$parent.selectGameAreaId = null;
        this.$parent.selectGameAreaName = "全区";

        this.$parent.selectGameServerName = "全服"

      }else{
        this.isQuanqu = false

          this.$parent.displayServerName = e.name
          this.$parent.selectGameServerId = e.id

        if (!this.$parent.selectGameAreaId) {
          this.$parent.selectGameAreaId = this.gameAreaList[0].id
          this.$parent.selectGameAreaName = this.gameAreaList[0].name
        }
        this.$parent.selectGameServerName = e.name;
      }
      this.$parent.refreshList("SERVER");
      this.$parent.isServerShow = false;
      //增加浏览记录
      if (this.$isLocalStorageSupported()) {
        if (this.isFromName == "游戏帐号") {
          this.$saveBrowseHistory({
            gameId: this.$route.params.gameId,
            gameName: this.$route.params.gameName,
            gameType: 1,
            goodsType: 2,
            typeName: "游戏帐号",
            areaId: this.$parent.selectGameAreaId,
            areaName: this.$parent.selectGameAreaName,
            serverId: this.$parent.selectGameServerId,
            serverName: this.$parent.selectGameServerName
          });
        } else {
          this.$saveBrowseHistory({
            gameId: this.$route.params.gameId,
            gameName: this.$route.params.gameName,
            gameType: 1,
            goodsType: 1,
            typeName: "装备",
            areaId: this.$parent.selectGameAreaId,
            areaName: this.$parent.selectGameAreaName,
            serverId: this.$parent.selectGameServerId,
            serverName: this.$parent.selectGameServerName
          });
        }
      }
        let arr = {
            createTime:new Date().getTime(),
            gameId: this.$route.params.gameId,
            gameName: this.$route.params.gameName,
            regionId: this.$parent.selectGameAreaId,
            regionName: this.$parent.selectGameAreaName,
            serverId: this.$parent.selectGameServerId,
            serverName: this.$parent.selectGameServerName,
            serviceProviderId:'',
            serviceProviderName:'',
            userId:'',
        }
       if (localStorage.getItem('qfList')) {
          let brr = localStorage.getItem('qfList') ? JSON.parse(localStorage.getItem('qfList')) :[];
         if (brr != '') {
            //处理:点击历史记录的广东区/广东1区，再次点击服务器，选择广东区/广东4区，广东区/广东4区未被记录
            if (brr[0].serverName == arr.serverName && brr[0].regionName == arr.regionName) {
            //       不删除,不添加,因为localstorage已有,
            }else{
              brr.unshift(arr)
            }
        this.historyList=brr;
        localStorage.setItem('qfList',JSON.stringify(this.historyList));
        
         }else{
         this.historyList.unshift(arr);
        localStorage.setItem('qfList',JSON.stringify(this.historyList));
         }
       }
      //  else{
      //    this.historyList.unshift(arr);
      //    localStorage.setItem('qfList',JSON.stringify(this.historyList));
      //  }
      
    },
    hisClick(item) {
      let self = this;
      self.$parent.isPost = true;
      //---------------搜索点击的区服的商品列表 ------------------
      self.isQuanqu = false;
      self.$parent.displayServerName = item.serverName;
      self.$parent.selectGameServerId = item.serverId;
      self.$parent.selectGameServerName = item.serverName;
      //点击历史记录,在本地数组中删除这一条后再添加到首位
      self.historyList.forEach((value, index) => {
        if (value.serverName == item.serverName ) {
          self.historyList.splice(index, 1);      
        }
      });
       item.createTime = new Date().getTime();
      self.historyList.unshift(item);
        localStorage.setItem('qfList',JSON.stringify(self.historyList));
      if (self.$parent.isLogin) {
           self.postHistory()    
      }
      //应该加个判断/点击历史记录的时候加个东西判断电机的是历史记录,不是其他服
      //更新区后显示之前选中的是历史记录    
        this.$parent.selectGameAreaId = item.regionId;
        this.$parent.selectGameAreaName = item.regionName;
        this.getPcGameServerList({
          aid: item.regionId
      });
        //将服显示在原  服务器的地方
      if (item.regionId == null ) {
      this.$parent.displayServerName = item.regionName + item.serverName;
      } else {
        this.$parent.displayServerName = item.serverName;        
      }
    
      //搜索所在服的商品列表
      this.$parent.selectGameServerId = item.serverId;
      this.$parent.selectGameServerName = item.serverName;
      this.$parent.refreshList("SERVER");
      this.$parent.isServerShow = false;
      //
      // localStorage.setItem("qfList", JSON.stringify(self.historyList));
    },
    //获取本地历史纪录
    getHistory(item) {
      if (!item) {
        
        let obj = JSON.parse(localStorage.getItem("qfList"));
        for (var key in obj) {
          if (obj[key].regionName) {
            this.historyList.push(obj[key]);
          }
        }
    
      } else {
        self.historyList = item;
      }
    },
    //将历史记录上传给服务器
    postHistory() {
      let resq;
    
      let params =localStorage.getItem("qfList") ? JSON.parse(localStorage.getItem("qfList")) : [{}];
      return new Promise((resolve, reject) => {
        this.$http
          .post(
            this.$CONSTANTS.APISearch +
              "regionServerHistory/insertCategoryHistory",
            { historyList: params }
          )
          .then(
            res => {
              resolve(res.body.responseStatus.code);
            },
            error => {
              reject(error);
            }
          );
      });
     
    },
    areaClick(e) {
      if(e==0){
        this.isQuanqu = true;
        this.isHis = false;
        this.$parent.selectGameAreaId = null;
        this.$parent.selectGameAreaName = "全区";
      } else if (e == "his") {
        // debugger
        this.isHis = true;
        //判断用户是否登录 如果登录 了 吧本地的 历史记录上传到服务器
    //未登录的情况下 读取本地的
     this.$getAccount().then(res=>{
        if(res){
          //接口获取历史记录 先把本地的记录传给接口
          this.$parent.isLogin=true
          if (this.$isLocalStorageSupported) { 
            //存到服务器
             let params =localStorage.getItem("qfList") ? JSON.parse(localStorage.getItem("qfList")) : [{}];
             console.log
             this.$http.post(this.$CONSTANTS.APISearch +"regionServerHistory/insertCategoryHistory", { historyList:params})
            //从服务器获取
             this.$http.post(this.$CONSTANTS.APISearch +"regionServerHistory/queryCategoryHistory",{ gameId: this.$route.params.gameId }).then(res => {
                     let arrs = [];
                 if (res.body.responseStatus.code == "00") {   
                     let arr= res.body.result;
                    if (arr) {
                       arr.forEach((item,index)=>{
                       if (item.gameId ==  this.$route.params.gameId) {
                         arrs.push(item)
                       }
                     })
                    }
                     }
                     localStorage.setItem('qfList', JSON.stringify(arrs))
                   this.historyList = arrs;
                 })
                 
          } 
          }else{
          this.$parent.isLogin=false
        let Darr = JSON.parse(localStorage.getItem("qfList"));
           if (this.$isLocalStorageSupported) {
          if (Darr) {
            let brr = [];
            Darr.forEach((item, index) => {
              if (this.$route.params.gameId == item.gameId) {
                brr.push(item);
              }
            });
                if (brr.length>20) {
                  let num = brr.length-20
                  brr.splice(20,num)
                }
                this.historyList = brr;
          }
           }
         }
       })

      } else {
        this.isQuanqu = false;
        this.isHis = false;
        this.$parent.selectGameAreaName = e.name;
        this.$parent.selectGameAreaId = e.id;
        this.getPcGameServerList({
            aid: e.id
        });
      }
      this.$parent.updatePostData("SERVER");
    },
    ...mapActions({
      getPcGameAreaList: "choice/ACTPCGAMEAREALIST",
      getPcGameServerList: "choice/ACTPCGAMESERVERLIST"
    })
  }
};
</script>
<style src='css/equipment/equipment-wjr.css'></style>
<style scoped>
.seach-list {
  position: relative;
  top: 1.92rem;
}

.gmvst-profile {
  z-index: 100;
  height: 8.34rem;
  overflow: hidden;
}

.shade {
  top: 2rem;
  display: block;
}

.gmvst-area ul {
  margin-top: 1.1rem;
}

.gmvst-area {
  height: 8.37rem;
}

.forscroll {
  height: 8.34rem;
  overflow-y: scroll;
}

.gmvst-area ul {
  height: 8.38rem;
}

.noserver {
  margin-top: 0.32rem;
  display: block;
}
</style>
